import _ from 'lodash';

import Storage from './storage';
import NavigationService from '../NavigationService';
import { ROUTERMAP } from './constants';

// const host = 'http://www.coinxp.io/'
// const host = 'https://cxp.com/';
const host = 'http://192.168.0.107:7001/';
// const host = 'http://localhost:7001/'

function requireResponse (response) {
    console.log('requireResponse...', response);
    if (response.status > 300) {
        return {error: `请求失败[${response.status}],${response.url}`}
    }
    return response.json()
}

interface response {
    status: string,
    retMsg: string,  // 返回的 msg
    data: any, // 返回的所有数据都在这里
    retCode: string, // 00 代表操作成功，
}

interface op{
    method: string,
    data?: {
        [key: string]: any,
    }
}

function handleResponse (result, cb, promise?: boolean){
    console.log('handle Response', result);
    // 约定为 token 不存在 或者 token 过期
    if (result.retCode && result.retCode === '999') {
        Storage.delete("token");
        Storage.delete("user");
        Storage.delete("address");
        return NavigationService.navigate(ROUTERMAP.login, {delUser: true});
    }
    if (result.error) {
        console.error('handleResponse error ', result.error);
        if (promise) {
            return Promise.reject(result.error)
        }
        return cb(result.error, null);
    }

    if (promise) {
        return Promise.resolve(result);
    }
    
    return cb(null, result);
}


/**
 * 
 * @param path 请求url
 * @param op {method: 方法，data: 数据}
 * @param promise 是否返回promise
 * @param cb 若 promise 为 false，则需要此参数作为回调
 */
const request = async (path: string, {method = 'GET', data = {}}:op, promise: boolean,  cb?: (err:Error, res: response) => void) :(Promise<any>) => {

    method = method.toUpperCase();
    let url = host + path;
    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };

    let body:any = {};

    if (method !== 'GET') {
        body = data;
    } else {

        let params = _.map(data, (v, k)=> [[k], JSON.stringify(v)].join('='));
        console.log('fetch..params', params);
        if (params.length) {
            // url = [url, encodeURIComponent(params.join('&'))].join('?');
            url = [url, params.join('&')].join('?');
        }
    }
    
    const fetchOption:any = {
        headers,
        method,
        // mode: 'cors',
    }

    if (method == 'POST') {
        fetchOption.body = JSON.stringify(body);
    }

    console.log('fetch request...', url, body, fetchOption);

   if (promise) {
       return new Promise((resolve, reject) => {
            fetch(url, fetchOption).then(res => {
                return requireResponse(res);
            }).then(res => {
                return resolve(handleResponse(res, null, true));
            }).catch(e => {
                return reject(e);
            })
       })
   }

    fetch(url, fetchOption).then(res => {
        return requireResponse(res);
    }).then(res => {
            return handleResponse(res, cb);
    }).catch(e => {
        console.error(new Error(e));
    })
}



export default request;
